//
//  LYBaseWKWebView.m
//  YiShopCustomer
//
//  Created by LJJ on 2018/3/28.
//  Copyright © 2018年 重庆市礼仪之邦电子商务有限公司. All rights reserved.
//

#import "LYBaseWKWebView.h"
#import "LJWebKitSupport.h"

@implementation LYBaseWKWebView

#pragma mark - 同步cookie到wkwebview
// 设置ajax cookie - 同域下ajax请求 iframe带上cookie
+ (void)setAjaxCookies {
    
    NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    NSMutableString *mCookies = [NSMutableString new];
    [mCookies appendString:@"document.cookie='"];//开头
    
    for (NSHTTPCookie *cookie in [cookieJar cookies]) {
        NSLog(@"%@",cookie);
        NSString *theCookie = [NSString stringWithFormat:@"%@=%@;",cookie.name,cookie.value];
        [mCookies appendString:theCookie];
    }
    
    [mCookies appendString:@"'"];//结尾
    
    if ([LJUtility theStringIsValid:mCookies]) {
        [[LJWebKitSupport sharedSupport].contentController removeAllUserScripts];

        WKUserScript *cookieScript = [[WKUserScript alloc]
                                      initWithSource:mCookies.copy
                                      injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
        
        [[LJWebKitSupport sharedSupport].contentController addUserScript:cookieScript];
    }
}

+ (NSString *)getCookieValue {
    // 在此处获取返回的cookie
    NSMutableDictionary *cookieDic = [NSMutableDictionary dictionary];
    NSMutableString *cookieValue = [NSMutableString stringWithFormat:@""];
    NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    for (NSHTTPCookie *cookie in [cookieJar cookies]) {
        [cookieDic setObject:cookie.value forKey:cookie.name];
        NSLog(@"%@",cookie);
    }
    // LYZB +userId和lbsToken
//    NSString *usrId = [YSCApp sharedInstance].userID;
//    NSString *token =  [YSCApp sharedInstance].lbsToken;
    // cookie重复，先放到字典进行去重，再进行拼接
    for (NSString *key in cookieDic) {
        id value = [cookieDic valueForKey:key];
//        if ([key isEqualToString:@"USER_ID"] && [YSCUtils theStringIsValid:usrId]) {
//            value = usrId;
//        } else if ([key isEqualToString:@"LBS_TOKEN"] && [YSCUtils theStringIsValid:token]) {
//            value = token;
//        }
        NSString *appendString = [NSString stringWithFormat:@"%@=%@;", key, value];
        [cookieValue appendString:appendString];
    }
//    NSString *cookieUsrId = [cookieDic safeObjectForKey:@"USER_ID"];
//    NSString *cookieLbsToken = [cookieDic safeObjectForKey:@"LBS_TOKEN"];
//    if (![YSCUtils theStringIsValid:cookieUsrId] && [YSCUtils theStringIsValid:usrId]) {
//        NSString *appendString = [NSString stringWithFormat:@"%@=%@;", @"USER_ID", usrId];
//        [cookieValue appendString:appendString];
//    }
//    if (![YSCUtils theStringIsValid:cookieLbsToken] && [YSCUtils theStringIsValid:token]) {
//        NSString *appendString = [NSString stringWithFormat:@"%@=%@;", @"LBS_TOKEN", token];
//        [cookieValue appendString:appendString];
//    }
    return cookieValue;
}

//request请求带上cookie(主要是首次request)
- (WKNavigation *)loadRequest:(NSMutableURLRequest *)request
{
    NSMutableURLRequest *mReq = [NSMutableURLRequest requestWithURL:request.URL];
    NSString *cookieValue = [LYBaseWKWebView getCookieValue];
    if (cookieValue && ![cookieValue isEqualToString:@""]) {
        [mReq setValue:cookieValue forHTTPHeaderField:@"Cookie"];
    }
    return [super loadRequest:mReq];
}

- (instancetype)init {
    [LYBaseWKWebView setAjaxCookies];
    self = [super initWithFrame:CGRectZero configuration:[LJWebKitSupport sharedSupport].webViewConfiguration];
    if (self) {
        [self setUserAgentInfo];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame {
    [LYBaseWKWebView setAjaxCookies];
    self = [super initWithFrame:frame configuration:[LJWebKitSupport sharedSupport].webViewConfiguration];
    if (self) {
        [self setUserAgentInfo];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame configuration:(nonnull WKWebViewConfiguration *)configuration {
    [LYBaseWKWebView setAjaxCookies];
    self = [super initWithFrame:frame configuration:configuration];
    if (self) {
        [self setUserAgentInfo];
    }
    return self;
}

- (void)setUserAgentInfo {
    // userAgent设置
    [self evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
        NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
        // app版本
        NSString *appVer = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
        NSString *oldAgent = result;
        NSString *newAgent;
        // 给User-Agent添加额外的信息 - 区分来自哪个app
        if ([LJUtility theString:oldAgent containSting:@"ggwq_cq"]) { // 已有就不加了
            newAgent = oldAgent;
        } else {
            newAgent = [NSString stringWithFormat:@"%@;AppInfo:appName=%@&&appVer=%@", oldAgent, @"ggwq_cq", appVer]; // 没有就加
        }
        // 设置global User-Agent
        NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:newAgent, @"UserAgent", nil];
        [[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
        [[NSUserDefaults standardUserDefaults] synchronize];
        if (@available(iOS 9.0, *)) {
            [self setCustomUserAgent:newAgent];
        }
    }];
}
@end

